package com.mdnote.jianzhi_offer.stack;

import java.util.ArrayDeque;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/10/12
 * @description 两个队列实现一个栈
 */
public class Offer09II {

    public static void main(String[] args) {
        MyStack myStack = new MyStack();
        myStack.append(11);
        myStack.append(12);
        myStack.append(13);

        System.out.println(myStack.delete());
        System.out.println(myStack.delete());
        System.out.println(myStack.delete());
        myStack.append(14);
        myStack.append(15);
        System.out.println(myStack.delete());
        myStack.append(16);
        System.out.println(myStack.delete());
        System.out.println(myStack.delete());


    }

    private static class MyStack {

        private ArrayDeque<Integer> queue1;
        private ArrayDeque<Integer> queue2;

        MyStack() {
            this.queue1 = new ArrayDeque<>();
            this.queue2 = new ArrayDeque<>();
        }

        public void append(int val) {
            if (!queue1.isEmpty()) {

                queue1.offerLast(val);
            } else {
                queue2.offerLast(val);
            }
        }

        public int delete() {
            ArrayDeque<Integer> isEmpty = queue1.isEmpty() ? queue1 :queue2;
            ArrayDeque<Integer> noEmpty = queue1.isEmpty() ? queue2 :queue1;

            if (isEmpty == noEmpty) {
                throw new RuntimeException("stack is empty");
            }
            while (noEmpty.size() != 1) {
                isEmpty.offerLast(noEmpty.removeFirst());
            }

            return noEmpty.removeLast();
        }
    }
}
